package cn.itcast.service.impl;

import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.RoleService;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Reference
   private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            if (username == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }

            //根据用户名获取用户
            User useryh = userService.findByName(username);
            if (useryh == null) {
                return null;
            } else {
//                Set<Role> roleList = new HashSet<>();
                List<GrantedAuthority> list = new ArrayList<>();
//                List<Integer> roleIdList = this.userService.findRoleIdsById(useryh.getId());
//                for (Integer roleId : roleIdList) {
//                    Role role = this.roleService.findById(roleId);
//                    roleList.add(role);
//
//                }
//                useryh.setRoles(roleList);
//                //获取用户角色
//                Set<Role> roles = useryh.getRoles();
//                for (Role role : roles) {
//                    //为用户授予角色
//                    list.add(new SimpleGrantedAuthority(role.getKeyword()));
//                    //根据角色获取权限集合
//                    Set<Permission> permissions = role.getPermissions();
//                    //为用户授予权限
//                    for (Permission permission : permissions) {
//                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
//                    }
//                }
                org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(username, useryh.getPassword(), list);
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
